package controller;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import core.*;

public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) {
		CurrentUser user = new CurrentUser(request);
		if(user.isLoggedIn()){
			View.showMessage(request, response, "You have already logged in.", "Index");
			return;
		}
		
		String email = "";
		String password = "";
		String notify = "";

		try {
			email = request.getParameter("email");
			password = request.getParameter("password");
			
			if(user.login(email, password)){
				response.sendRedirect("Index");
			}else{
				notify = "Please check your input and try again";
				request.setAttribute("notify", notify);
				View.show(request, response, "login");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		CurrentUser user = new CurrentUser(request);
		if(user.isLoggedIn()){
			View.showMessage(request, response, "You have already logged in.", "Index");
			return;
		}
		
		View.show(request, response, "login");
	}
}
